import Phaser from "phaser";

export default class GameScene extends Phaser.Scene {
  // Phaser 游戏对象声明
  private bird!: Phaser.Physics.Matter.Image;
  private pipes!: Phaser.Physics.Matter.Image[];

  // 新增：射线相关属性
  private rayGraphics!: Phaser.GameObjects.Graphics; // 射线图形对象
  private rayLength: number = 0; // 射线长度
  private maxRayLength: number = 300; // 最大射线长度
  private isSpaceDown: boolean = false; // 空格键是否按下
  private rayGrowthSpeed: number = 500; // 射线增长速度（像素/秒）
  private rayShrinkSpeed: number = 1000; // 射线收缩速度（像素/秒）

  // 旋转速度
  private rotationSpeed: number = 300; // 旋转速度（度/秒）

  private qKey!: Phaser.Input.Keyboard.Key; // Q 键
  private eKey!: Phaser.Input.Keyboard.Key; // E 键

  private hookPoint: Phaser.Math.Vector2 | null = null; // 钩锁固定点
  private isHooked: boolean = false; // 是否处于钩锁状态
  private hookForce: number = 800; // 钩锁拉力强度
  private swingForce: number = 300; // 摆动施加力
  private maxSwingSpeed: number = 600; // 最大摆动速度

  private isLeverJumping: boolean = false; // 是否处于杠杆跳跃状态
  private jumpForce: number = 1200; // 基础跳跃力
  private gravityScale: number = 0.6; // 跳跃时重力缩放系数
  private jumpCooldown: number = 800; // 跳跃冷却时间（毫秒）
  private lastJumpTime: number = 0; // 上次跳跃时间
  private shiftKey!: Phaser.Input.Keyboard.Key; // Shift键

  constructor() {
    super("Game");
  }

  preload() {}

  create() {
    this.initGameWorld();
    this.setupCollisions();
    this.setupInput();

    // 初始化射线图形对象
    this.rayGraphics = this.add.graphics();
  }

  private initGameWorld() {
    // 场景初始化
    this.add.image(640, 360, "background").setDisplaySize(1280, 720);

    // 玩家角色
    // this.bird = this.physics.add
    //   .image(60, 60, "bird")
    //   .setCollideWorldBounds(true)
    //   .setBounce(0.5, 0.5); // 添加反弹系数
    this.bird = this.matter.add.sprite(60, 60, "bird", undefined, {
      shape: "circle", // 使用圆形碰撞体
      chamfer: { radius: 14 }, // 碰撞体半径
      frictionAir: 0.02, // 空气阻力
      restitution: 0.5, // 弹性系数
    });

    // // 创建障碍物组
    // this.pipes = this.physics.add.group({
    //   frameQuantity: 3,
    //   immovable: true,
    //   allowGravity: false,
    // });

    // // 添加几个漂浮的障碍物
    // this.addFloatingPipe(300, 550);
    // this.addFloatingPipe(600, 500);
    // this.addFloatingPipe(800, 300);
    this.pipes = [
      this.createMatterPipe(300, 550),
      this.createMatterPipe(600, 500),
      this.createMatterPipe(800, 300),
    ];
  }
  private createMatterPipe(x: number, y: number) {
    const pipe = this.matter.add.image(x, y, "pipe", undefined, {
      isStatic: true, // 设置为静态物体
      collisionFilter: { category: 0x0002 }, // 碰撞分类
    });
    return pipe;
  }

  private addFloatingPipe(x: number, y: number) {
    const pipe = this.pipes.add(this.physics.add.image(x, y, "pipe"));
  }

  // private setupCollisions() {
  //   // 碰撞检测
  //   this.physics.add.collider(this.bird, this.pipes, () => {}, undefined, this);
  // }
  private setupCollisions() {
    this.matter.world.on(
      "collisionactive",
      (event: Matter.Events.CollisionActiveEvent) => {
        event.pairs.forEach((pair) => {
          if (
            (pair.bodyA === this.bird.body || pair.bodyB === this.bird.body) &&
            this.pipes.some(
              (pipe) => pipe.body === pair.bodyA || pipe.body === pair.bodyB,
            )
          ) {
            // 处理碰撞逻辑
          }
        });
      },
    );
  }

  private setupInput() {
    const cursor = this.input.keyboard?.createCursorKeys();
    if (!cursor) return;

    cursor?.space?.on("down", () => {
      this.isSpaceDown = true;
    });

    cursor?.space?.on("up", () => {
      this.isSpaceDown = false;
    });

    // 监听按键按下事件
    cursor.up.on("down", () => {
      this.bird.setVelocityY(-500);
    });
    cursor.down.on("down", () => {
      this.bird.setVelocityY(500);
    });
    cursor.left.on("down", () => {
      this.bird.setVelocityX(-260);
    });
    cursor.right.on("down", () => {
      this.bird.setVelocityX(260);
    });
    // 监听按键抬起事件
    cursor.left.on("up", () => {
      if (!cursor.right.isDown) this.bird.setVelocityX(0);
    });
    cursor.right.on("up", () => {
      if (!cursor.left.isDown) this.bird.setVelocityX(0);
    });
    cursor.up.on("up", () => {
      if (!cursor.down.isDown) this.bird.setVelocityY(0);
    });
    cursor.down.on("up", () => {
      if (!cursor.up.isDown) this.bird.setVelocityY(0);
    });

    // 初始化 Q 和 E 键 和 Shift 键
    if (this.input.keyboard) {
      this.qKey = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.Q);
      this.eKey = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.E);
      this.shiftKey = this.input.keyboard.addKey(
        Phaser.Input.Keyboard.KeyCodes.SHIFT,
      );
    }
  }

  // private drawRay() {
  //   // 清除之前的射线
  //   this.rayGraphics.clear();

  //   if (this.rayLength > 0) {
  //     // 设置射线样式
  //     this.rayGraphics.lineStyle(4, 0xff0000); // 红色射线，宽度为 4

  //     // 获取 bird 的中心点坐标
  //     const birdCenterX = this.bird.x;
  //     const birdCenterY = this.bird.y;

  //     // 根据 bird 的旋转角度计算射线方向
  //     const angleInRadians = Phaser.Math.DegToRad(this.bird.angle); // 将角度转换为弧度
  //     const rayEndX = birdCenterX + Math.cos(angleInRadians) * this.rayLength;
  //     const rayEndY = birdCenterY + Math.sin(angleInRadians) * this.rayLength;

  //     let hit = this.physics.raycast(
  //       new Phaser.Math.Vector2(this.bird.x, this.bird.y),
  //       new Phaser.Math.Vector2(rayEndX, rayEndY),
  //     );

  //     if (hit.length > 0) {
  //       // 绘制碰撞点
  //       this.rayGraphics.fillStyle(0x00ff00, 1);
  //       this.rayGraphics.fillCircle(hit[0].x, hit[0].y, 8);

  //       // 如果处于发射状态且未钩住，设置钩点
  //       if (this.isSpaceDown && !this.isHooked) {
  //         this.hookPoint = new Phaser.Math.Vector2(hit[0].x, hit[0].y);
  //         this.isHooked = true;
  //       }
  //     }

  //     // 绘制射线
  //     this.rayGraphics.beginPath();
  //     this.rayGraphics.moveTo(birdCenterX, birdCenterY); // 起点
  //     this.rayGraphics.lineTo(rayEndX, rayEndY); // 终点
  //     this.rayGraphics.strokePath();
  //   }
  // }
  private drawRay() {
    const from = new Phaser.Math.Vector2(this.bird.x, this.bird.y);
    const angle = Phaser.Math.DegToRad(this.bird.angle);
    const to = from
      .clone()
      .add(
        new Phaser.Math.Vector2(Math.cos(angle), Math.sin(angle)).scale(
          this.rayLength,
        ),
      );

    // 使用Matter.js的射线检测
    const hits = this.matter.query.ray(
      this.matter.world.getAllBodies(),
      from,
      to,
    );

    if (hits.length > 0) {
      const closestHit = hits.reduce((prev, curr) =>
        curr.distance < prev.distance ? curr : prev,
      );

      // 绘制碰撞点
      this.rayGraphics.fillStyle(0x00ff00, 1);
      this.rayGraphics.fillCircle(closestHit.point.x, closestHit.point.y, 8);
    }
  }

  update(time: number, delta: number) {
    // this.physics.world.update(time, delta);

    // 更新射线长度
    if (this.isSpaceDown) {
      // 按下空格键时增长射线，但不超过最大长度
      this.rayLength += (this.rayGrowthSpeed * delta) / 1000;
      this.rayLength = Math.min(this.rayLength, this.maxRayLength); // 限制最大长度
    } else {
      // 抬起空格键时收缩射线
      this.rayLength -= (this.rayShrinkSpeed * delta) / 1000;
      this.rayLength = Math.max(this.rayLength, 0); // 防止射线长度为负
    }

    // 持续旋转 bird
    if (this.qKey?.isDown) {
      this.bird.angle -= (this.rotationSpeed * delta) / 1000; // 逆时针旋转
      // this.bird.setAngularVelocity(-this.rotationSpeed); // 逆时针旋转
    }
    if (this.eKey?.isDown) {
      this.bird.angle += (this.rotationSpeed * delta) / 1000; // 顺时针旋转
      // this.bird.setAngularVelocity(this.rotationSpeed);
    }

    if (this.isHooked && this.hookPoint) {
      // 计算方向向量
      const direction = new Phaser.Math.Vector2(
        this.hookPoint.x - this.bird.x,
        this.hookPoint.y - this.bird.y,
      ).normalize();

      // 施加基础拉力
      this.bird.setVelocity(
        direction.x * this.hookForce,
        direction.y * this.hookForce,
      );

      // 摆动控制（使用Q/E键）
      if (this.qKey?.isDown) {
        const perpendicular = new Phaser.Math.Vector2(
          -direction.y,
          direction.x,
        );
        this.bird.setVelocityX(
          this.bird.body!.velocity.x + perpendicular.x * this.swingForce,
        );
      }
      if (this.eKey?.isDown) {
        const perpendicular = new Phaser.Math.Vector2(
          direction.y,
          -direction.x,
        );
        this.bird.setVelocityX(
          this.bird.body!.velocity.x + perpendicular.x * this.swingForce,
        );
      }

      // 速度限制
      this.bird.body!.velocity.limit(this.maxSwingSpeed);

      // 自动旋转朝向运动方向
      const angle = Phaser.Math.RadToDeg(
        Math.atan2(this.bird.body!.velocity.y, this.bird.body!.velocity.x),
      );
      this.bird.setRotation(angle + 90); // +90度修正精灵朝向

      // 杠杆跳跃检测
      if (
        Phaser.Input.Keyboard.JustDown(this.shiftKey) &&
        this.time.now > this.lastJumpTime + this.jumpCooldown
      ) {
        // 计算跳跃方向（与钩锁点反向）
        const jumpDirection = new Phaser.Math.Vector2(
          this.bird.x - this.hookPoint.x,
          this.bird.y - this.hookPoint.y,
        ).normalize();

        // 应用跳跃力
        this.bird.setVelocity(
          jumpDirection.x * this.jumpForce,
          jumpDirection.y * this.jumpForce,
        );

        // 跳跃状态设置
        this.isHooked = false;
        this.hookPoint = null;
        this.isLeverJumping = true;
        this.lastJumpTime = this.time.now;

        // 跳跃时临时重力调整
        this.physics.world.gravity.y *= this.gravityScale;
      }
    }
    // 跳跃状态更新
    if (this.isLeverJumping) {
      // 动态恢复重力（平滑过渡）
      this.physics.world.gravity.y = Phaser.Math.Linear(
        this.physics.world.gravity.y,
        1200, // 基础重力值
        0.1, // 过渡速度
      );

      // 速度限制
      this.bird.body!.velocity.limit(1500);

      // 重置状态检测
      if (this.bird.body!.velocity.y > 0) {
        this.isLeverJumping = false;
      }
    }

    // 松开空格时解除钩锁
    if (!this.isSpaceDown && this.isHooked) {
      this.isHooked = false;
      this.hookPoint = null;
      this.bird.setAngularVelocity(0); // 停止旋转
    }

    // 绘制射线
    this.drawRay();
  }

  destroy() {}
}
